package com.github.boluo1230.wechat.controller;

import com.github.boluo1230.wechat.entity.MpApp;
import com.github.boluo1230.wechat.entity.vo.WxAccessToken;
import com.github.boluo1230.wechat.service.mp.MpAppService;
import com.github.boluo1230.wechat.service.mp.WeChatService;
import com.github.boluo1230.wechat.util.WeixinUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Code Farmer
 * @date 2019/10/12 20:12
 */
@RestController
@RequestMapping("")
@AllArgsConstructor
public class IndexController {

    private final WeChatService weChatService;
    private final MpAppService mpAppService;

    @RequestMapping("/{appId}")
    public String weChat(@PathVariable String appId, HttpServletRequest request,
                         @RequestBody(required = false) String requestBody) throws Exception {

        MpApp mpApp = mpAppService.findMpApp(appId);

        if (mpApp == null) {
            throw new Error("find no mpApp:" + appId);
        }

        String signature = request.getParameter("signature");
        String echoStr = request.getParameter("echostr");
        List<String> signatureList = WeixinUtil.getMessageSignatureList(request, mpApp.getSignToken());

        boolean isPost = request.getMethod().toLowerCase().equals("post");
        if (!WeixinUtil.checkSignature(signature, signatureList)) {
            return "fail";
        }
        if (StringUtils.isNotBlank(echoStr)) {
            return echoStr;
        }

        if (isPost) {
            return weChatService.handle(requestBody, mpApp);
        }

        return "success";
    }

    @GetMapping("/token")
    public WxAccessToken getAccessToken(String appId, String type, String signature) {
        return weChatService.getAccessToken(appId, type, signature);
    }

}
